import { Decimal } from 'decimal.js'

// x+y
export const add = (x, y, fixed = 4) => {
    return new Decimal(x)
        .add(new Decimal(y))
        .toNumber()
        .toFixed(fixed)
}
// x-y
export const sub = (x, y, fixed = 4) => {
    return new Decimal(x)
        .sub(new Decimal(y))
        .toNumber()
        .toFixed(fixed)
}
// x/y
export const div = (x, y, fixed = 4) => {
    return new Decimal(x)
        .div(new Decimal(y))
        .toNumber()
        .toFixed(fixed)
}
// x*y
export const mul = (x, y, fixed = 4) => {
    return new Decimal(x)
        .mul(new Decimal(y))
        .toNumber()
        .toFixed(fixed)
}
// |n|
export const abs = (x, fixed = 4) => {
    return new Decimal(x)
        .abs()
        .toNumber()
        .toFixed(fixed)
}
// 千分位
export const price = (n, fixed = 4) => {
    return Number(n)
        .toFixed(fixed)
        .toString()
        .replace(/(\d)(?=(?:\d{3})+(?:\.))/g, '$1,')
}
// 求平均值, 入参number数组
export const avrg = (arr, fixed = 4) => {
    return arr
        .reduce((pre, cur, i, a) =>
            i < a.length - 1 ? pre + cur : (pre + cur) / a.length
        )
        .toFixed(fixed)
}
